package com.xbf.controller;

import com.xbf.entity.Goods;
import com.xbf.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping("/add")
    public boolean addGoods(@RequestBody Goods goods) {
        return goodsService.save(goods);
    }

    @GetMapping("/{id}")
    public Goods getGoodsById(@PathVariable Integer id) {
        return goodsService.getById(id);
    }

    @PutMapping("/update")
    public boolean updateGoods(@RequestBody Goods goods) {
        return goodsService.updateById(goods);
    }

    @DeleteMapping("/{id}")
    public boolean deleteGoods(@PathVariable Integer id) {
        return goodsService.removeById(id);
    }

    @PostMapping("/reduceStock")
    public Map<String, Object> reduceStock(@RequestParam Integer goodsId, @RequestParam Integer quantity) {
        Map<String, Object> result = new HashMap<>();
        boolean success = goodsService.reduceStock(goodsId, quantity);
        result.put("success", success);
        result.put("message", success ? "库存减少成功" : "库存不足");
        return result;
    }

    // 新增获取所有商品的API
    @GetMapping("/all")
    public List<Goods> getAllGoods() {
        return goodsService.getAllGoods();
    }
}